import { Tabs } from "antd";
import React, { Component } from "react";
import Inquiry_detail from "./Detail";
import Inquiry_edit from "./Edit";
import Inquiry_list from "./InquiryList";
import qs from "querystring";

const { TabPane } = Tabs;

export default class InquiryManagement extends Component {
  constructor(props) {
    super(props);
    this.newTabIndex = 0;
    //获取MySider传来的user_id
    const { state } = this.props.location;
    const user_id = Number(qs.stringify(state).slice(8));
    const panes = [
      {
        title: "询价单列表",
        content: <Inquiry_list handleClick={this.add} user_id={user_id} />, //这里指传给list，用以判断按钮权限
        key: "1",
        closable: false,
      },
    ];
    this.state = {
      // activeKey为当前展示页面对应的key
      activeKey: panes[0].key,
      panes,
    };
  }
  // 点击的tabs发生变化，就将state中的activeKey变为当前的activeKey，state一变就会重新渲染，tabs就可以接到当前应该指向的页面
  onChange = (activeKey) => {
    this.setState({ activeKey });
  };
  // 在这里应该进行一下判断，如果activeKey是1则重新加载一下数据库数据

  onEdit = (targetKey, action) => {
    this[action](targetKey);
  };

  add = (editable, record) => {
    const { panes } = this.state;
    const activeKey = `newTab${this.newTabIndex++}`;
    if (editable) {
      panes.push({
        title: "编辑询价单",
        content: <Inquiry_edit id={record.id} />,
        key: activeKey,
        closable: true,
      });
    } else {
      panes.push({
        title: "询价单详情",
        content: <Inquiry_detail id={record.id} />,
        key: activeKey,
        closable: true,
      });
    }

    this.setState({ panes, activeKey });
  };

  remove = (targetKey) => {
    let { activeKey } = this.state;
    let lastIndex;
    this.state.panes.forEach((pane, i) => {
      if (pane.key === targetKey) {
        lastIndex = i - 1;
      }
    });
    const panes = this.state.panes.filter((pane) => pane.key !== targetKey);
    if (panes.length && activeKey === targetKey) {
      if (lastIndex >= 0) {
        activeKey = panes[lastIndex].key;
      } else {
        activeKey = panes[0].key;
      }
    }
    this.setState({ panes, activeKey });
  };

  render() {
    return (
      // 整个是一个div，div里有一个tab组件，通过遍历state中的panes来自动生成pane，每一个都返回一个tabpane组件
      <div>
        <Tabs
          hideAdd
          onChange={this.onChange}
          activeKey={this.state.activeKey}
          type="editable-card"
          onEdit={this.onEdit}
        >
          {this.state.panes.map((pane) => (
            <TabPane tab={pane.title} key={pane.key} closable={pane.closable}>
              {pane.content}
            </TabPane>
          ))}
        </Tabs>
      </div>
    );
  }
}
